<template>
<div class="app-container">
    <!-- 功能性按钮 -->
        <el-form :inline="true" :model="query" size="mini">
            <el-form-item label="角色名称:">
                <el-input v-model.trim="query.name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
                <el-button  icon="el-icon-refresh" @click="reload">重置</el-button>
                <el-button  icon="el-icon-plus" type="primary"  @click="openAdd" v-if="!roleIds"> 新增</el-button>
                <el-button  icon="el-icon-plus" type="success"  @click="handleUserRole" v-if="roleIds"> 设置角色</el-button>
            </el-form-item>
        </el-form>
     <!-- 表格主体 -->
        <el-table 
            :data="list" 
            stripe
            border 
            row-key="id"
            highlight-current-row
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <!--  reserve-selection必须配合上面的row-key使用，这样可以在切换页码后，保留前面选中的行 -->
            <el-table-column  v-if="roleIds" type="selection"  reserve-selection align="center" width="60"></el-table-column>
            <el-table-column  label="序号" width="60" type="index"></el-table-column>
            <el-table-column prop="name" align="center" label="角色名称"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column  label="操作" v-if="!roleIds" >
                 <template slot-scope="scope">
                    <el-button type="success" @click="handlePermission(scope.row.id)" size="mini">分配权限</el-button>
                    <el-button type="primary" @click="handleEdit(scope.row.id)" size="mini">编辑</el-button>
                    <el-button type="danger"  @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
                </template>
            </el-table-column>            
        </el-table>

    <!-- 分页组件 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.current"
            :page-sizes="[10, 20, 50]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
        </el-pagination>

    <!-- 弹窗 -->
    <edit :title="edit.title" :visible="edit.visible" :formData="edit.formData" :remoteClose="remoteClose" />
    <permission title="分配权限" :roleId="per.roleId" :visible="per.visible" :remoteClose="remotePerClose" />
</div>
</template>

<script>

import api from "@/api/role"

import Edit from "./edit.vue"

import Permission from "./permission.vue"

export default {
    name:"Role",
    //当前用户管理模块，将当前这个组件文件作为子组件时,进行接收父组件传递过来的属性
    props:{
        roleIds:null
    },
    data(){
        return {
            list:[],
            page:{
                current:1,
                size:20,
                total:0
            },
            query:{},
            edit:{
                title:'',
                visible:false,
                formData:{}
            },
            per:{ 
                visible:false,
                roleId:null //角色ID
            },
            chekedRoleList:[]  //存储选中的对象
        }
    },
    components:{
        Edit,
        Permission
    },
    created(){
        this.fetchData()
    },
    watch:{
        roleIds(){
            this.query = {} //清空查询框数据
            this.queryData() //重新获取数据
        }
    },
    methods:{
        //最初的列表渲染
        async fetchData(){
            const {data} = await api.getList(this.query,this.page.current,this.page.size)
            this.list = data.records
            this.page.total = data.total
            //列表有数据后勾选角色
            this.chekedRoles()
        },
        //勾选角色
        chekedRoles(){
            //清空上一次选择的
            this.$refs.multipleTable.clearSelection();
            if(this.roleIds){
                //循环出查询到的所有角色数据，要进行判断父组件的roleIds中的每个角色对象
                this.list.forEach(item=>{
                    //拿到列表中的每一条记录的id与当前已经有的id进行匹配，匹配到了则应该选中
                    if(this.roleIds.indexOf(item.id) !== -1){
                        //选中，对应传递的是角色对象
                        this.$refs.multipleTable.toggleRowSelection(item,true);
                    }
                    
                })
            }
        },
        //编辑
        async handleEdit(id){
            const res = await api.getById(id)
            if(res.code === 20000){
                this.edit.formData = res.data
            }
            //弹出窗口
            this.edit.title = "编辑"
            this.edit.visible = true
            
        },
        //删除
        async handleDelete(id){            
            this.$confirm('确认删除这个角色吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                //发送删除请求  
                api.deleteById(id).then(res=>{
                    //处理响应结果
                    this.$message({
                        type: res.code === 20000 ? "success":"error",
                        message: res.message
                    });
                  //刷新列表
                  this.fetchData()                   
                })          
            }).catch(() => {
                //取消删除
            });
        },
        //页码显示切换每页有多少条
        handleSizeChange(val){
            this.page.size = val,
            this.fetchData()
        },
        //页码改变后到此方法
        handleCurrentChange(val){
            this.page.current = val
            this.fetchData()
        },
        //条件查询
        queryData(){
            this.page.current = 1
            this.fetchData()
        },
        //重置
        reload(){
            this.query = {},
            this.fetchData()
        },
        //新增
        openAdd(){
            this.edit.visible = true
            this.edit.title = "新增" 
        },
        //关闭窗口
        remoteClose(){
            this.formData = {}
            this.edit.visible = false
            this.fetchData()
        },
        //分配权限窗口弹出
        handlePermission(id){
            //将点击的那个角色id传递给子组件，进行查询当前角色已经用用的菜单IDs
            this.per.roleId = id
            this.per.visible = true
        },
        //关闭分配权限弹窗
        remotePerClose(){
            this.per.visible = false
            this.per.roleId = null
            this.fetchData()
        },
        //收集被选中的角色
        handleSelectionChange(val){
            // console.log("收集被选中的角色:",val)
            //val是选中的每个对象，将选中的每个对象封装到val数组中
            this.chekedRoleList = val
        },
        //点击设置角色按钮触发的
        handleUserRole(){
            const checkedRoleIds = []
            //获取每个元素中的id,因为调用保存角色接口，只需要选中的角色id
            this.chekedRoleList.forEach(item=>{
               checkedRoleIds.push(item.id)
            })
            //触发父组件的事件函数
            this.$emit("saveUserRole",checkedRoleIds)
        }
    }

}
</script>

<style scoped>

</style>
